<template>
    <a-card>
        <a-space>
            <a-select
                v-model:value="selected"
                style="width: 300px"
                placeholder="选择坐标转换类型"
            >
                <a-select-option v-for="d in selectList" :key="d.value">
                    {{ d.title }}
                </a-select-option>
            </a-select>
            <a-upload
                v-model:fileList="fileList"
                name="file"
                :action="action"
                @change="handleChange"
                style="width: 100px"
            >
                <a-button type="primary"><UploadOutlined /> 上传</a-button>
            </a-upload>
            <a-button type="primary" @click="onExport"
                ><DownloadOutlined /> 导出</a-button
            >
        </a-space>
    </a-card>
    <a-card style="margin-top: 10px">
        <a-table
            class="ant-table-striped"
            :pagination="{
                pageSize: formState.pageSize,
                total: total,
                showTotal: (total) => `共${total}条记录`,
                size: 'middle',
            }"
            :rowKey="(record) => record.id"
            :columns="columns"
            :data-source="repositories"
            :loading="tableLoading"
            :rowClassName="
                (record, index) => (index % 2 === 1 ? 'table-striped' : null)
            "
            size="small"
            @change="handleTableChange"
        >
            <template
                v-for="col in ['lat', 'lng', 'id']"
                #[col]="{ text, index }"
                :key="col"
            >
                <div>
                    <a-input
                        v-if="editableData[index]"
                        v-model:value="editableData[index][col]"
                    ></a-input>
                    <template v-else>
                        {{ text }}
                    </template>
                </div>
            </template>
            <template #operation="{ record, index }">
                <span v-if="editableData[index]">
                    <a-tag color="success" @click="onSave(index)">保存</a-tag>
                </span>
                <span v-else>
                    <a-tag color="#108ee9" @click="onEdit(index)">编辑</a-tag>
                </span>
                <a-popconfirm
                    title="你确定删除这条数据?"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="onDel(record.id, index)"
                >
                    <a-tag color="red">删除</a-tag>
                </a-popconfirm>
            </template>
        </a-table>
    </a-card>
</template>

<script lang="ts">
import {
    defineComponent,
    reactive,
    toRefs,
    computed,
    UnwrapRef,
    onMounted,
} from "vue";
import {
    TableState,
    TableStateFilters,
} from "ant-design-vue/es/table/interface";
import useRepositoryNameSearch from "./useRepositoryNameSearch";
import { UploadOutlined, DownloadOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import * as API from "@/api/coordinate-convert";
import xlsx from "xlsx";
type Pagination = TableState["pagination"];
export default defineComponent({
    name: "transform",
    components: { UploadOutlined, DownloadOutlined },
    setup() {
        const formState = reactive<{
            id: string;
            lat: string;
            lng: string;
            pageNo: number | undefined;
            pageSize: number;
        }>({
            id: "",
            lat: "",
            lng: "",
            pageNo: 1,
            pageSize: 10,
        });
        const {
            total,
            repositories,
            getUserRepositories,
        } = useRepositoryNameSearch(formState);
        onMounted(getUserRepositories);
        const columns = [
            {
                title: "id",
                dataIndex: "id",
                key: "id",
                slots: { customRender: "id" },
                width: "20%",
            },
            {
                title: "经度",
                dataIndex: "lng",
                key: "lng",
                slots: { customRender: "lng" },
                width: "30%",
            },
            {
                title: "纬度",
                dataIndex: "lat",
                key: "lat",
                slots: { customRender: "lat" },
                width: "30%",
            },
            {
                title: "操作",
                key: "operation",
                slots: { customRender: "operation" },
                width: "20%",
            },
        ];
        // 编辑
        interface DataItem {
            id: string;
            lnt: string;
            lng: string;
        }
        const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

        // table
        const store = reactive({
            total,
            selected: undefined,
            tableLoading: false,
            repositories,
            selectList: [
                {
                    value: "gcj2BD09",
                    text: "火星坐标系=>百度坐标系",
                    title: "火星坐标系=>百度坐标系",
                },
                {
                    value: "bd092GCJ",
                    text: "百度坐标系=>火星坐标系",
                    title: "百度坐标系=>火星坐标系",
                },
                {
                    value: "bd092WGS",
                    text: "百度坐标系=>地球坐标系",
                    title: "百度坐标系=>地球坐标系",
                },
                {
                    value: "wgs2BD09",
                    text: "地球坐标系=>百度坐标系",
                    title: "地球坐标系=>百度坐标系",
                },
                {
                    value: "wgs2GCJ",
                    text: "地球坐标系=>火星坐标系",
                    title: "地球坐标系=>火星坐标系",
                },
                {
                    value: "gcj2WGS",
                    text: "火星坐标系=>地球坐标系",
                    title: "火星坐标系=>地球坐标系",
                },
            ],
            handleTableChange: (
                pagination: Pagination,
                filter: TableStateFilters,
                sorter: any
            ) => {
                store.tableLoading = true;
                formState.pageNo = pagination?.current;
                getUserRepositories().then(() => {
                    store.tableLoading = false;
                });
            },
            onEdit: (index: number) => {
                editableData[index] = Object.assign(
                    {},
                    store.repositories[index]
                );
            },
            onSave: (index: number) => {
                const editResult = Object.assign(
                    store.repositories[index],
                    editableData[index]
                );
                API.editApi(editResult).then(({ msg }: any) => {
                    message.success(msg);
                    delete editableData[index];
                });
            },
            onDel: (id: string, index: number) => {
                API.delApi(id).then(({ msg }: any) => {
                    store.repositories.splice(index, 1);
                    message.success(msg);
                });
            },
            onExport: () => {
                API.exportApi().then((data: any) => {
                    let header = ["id", "lng", "lat"];
                    let toSheet = xlsx.utils.json_to_sheet(store.repositories, {
                        header: header,
                    });
                    let work = {
                        SheetNames: ["nodejs-sheetname"],
                        Sheets: {
                            "nodejs-sheetname": Object.assign({}, toSheet),
                        },
                    };
                    xlsx.writeFile(work, `${new Date().getTime()}.xls`);
                });
            },
        });

        //上传
        interface fileItem {
            uid: string;
            name?: string;
            status?: string;
            response: any;
            url?: string;
        }
        interface FileInfo {
            file: fileItem;
            fileList: fileItem[];
        }
        const upload = reactive({
            fileList: [],
            handleChange: (info: FileInfo) => {
                if (info.file.status === "done" && info.file.response.success) {
                    store.repositories = info.file.response.result.coordinates;
                    message.success(`${info.file.name}上传成功`);
                }
            },
        });

        const action = computed(() => {
            return `${
                import.meta.env.VITE_APP_API_BASE_URL_2
            }/coordinate/converter/importExcel?type=${store.selected}`;
        });

        return {
            formState,
            columns,
            action,
            editableData,
            ...toRefs(store),
            ...toRefs(upload),
        };
    },
});
</script>
<style lang="less" scoped>
.ant-table-striped :deep(.table-striped) {
    background-color: #fafafa;
}
</style>